const _ = require('lodash');

function getArea(r) {
  console.log(r);// 被缓存
  return Math.PI * r * r;
}

let getAreaWithMemory = _.memoize(getArea);
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(4));

// 模拟memoize

function memoize(fn) {
  let cache = {};// 缓存
  return function () {
    let key = JSON.stringify(arguments);// 结果参数作为key
    cache[key] = cache[key] || fn.apply(fn, arguments);
    return cache[key]
  }
}


let getAreaWithMemory2 = memoize(getArea);
console.log(getAreaWithMemory2(4));
console.log(getAreaWithMemory2(4));
console.log(getAreaWithMemory2(4));
console.log(getAreaWithMemory2(4));

